<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
	<meta name="viewport" content="width=device-width, initial-scale=1"/>
	<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.min.css"/>
	<title>Insert title here</title>
	<script src="http://code.jquery.com/jquery-1.7.1.js"></script>
	<script src="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.min.js"></script>
	<script src="/socket.io/socket.io.js"></script>
	<script>
		$(document).ready(function() {
			function changeIcon(parent, from, to) {
				var target = $('.ui-btn-text', parent).next();
				target.removeClass(from).addClass(to);
			};
			
			function changeCount(index, count) {
				$('li[data-index=' + index + '] .ui-li-count').html(count);
			};
			
			// create socket
			var socket = io.connect();
			
			socket.on('count', function(data) {
				// change product count
				changeCount(data.index, data.count);
			});
			
			$('.product > a[data-icon]').toggle(function() {
				var index = $(this).attr('data-index');
				
				// create socket event
				socket.emit('cart', Number(index));
				
				changeIcon(this, 'ui-icon-check', 'ui-icon-back');
			}, function() {
				var index = $(this).attr('data-index');
				
				// ask if buy
				if(confirm('Do you want to buy this?')) {
					socket.emit('buy', Number(index));
					
					$(this).parent().remove();
					$('#listview').listview('refresh');
				}
				else {
					socket.emit('return', Number(index));
					changeIcon(this, 'ui-icon-back', 'ui-icon-check');
				}
			});
		});
	</script>
</head>
<body>
	<div data-role="page">
		<div data-role="header">
			<h1>Store</h1>
		</div>
		<div data-role="content">
			<ul id="listview" data-role="listview" data-insert="true" data-filter="true">
				<li data-role="list-divider">products</li>
				<% products.forEach(function(item, index) { %>
				<li class="product" data-index="<%=item.index%>">
					<a href="#">
						<img src="chrome.png"/>
						<h3><%= item.name %></h3>
						<p><%= item.price %> Won</p>
						<span class="ui-li-count"><%= item.count %></span>
					</a>
					<a href="#" data-icon="check" data-index="<%= item.index %>"></a>
				</li>
				<% }); %>
			</ul>
		</div>
	</div>
</body>
</html>